'use strict';

const Service = require('egg').Service;
const ulid = require('../public/ulid');

class CustomerService extends Service {
  async list(params) {
    const Op = this.ctx.modelmysql.Sequelize.Op;
    const where = {};
    where.tid = params.tid;
    if (params.name) {
      where.name = { [Op.like]: '%' + params.name + '%' };
    }
    return await this.ctx.modelmysql.Customer.findAndCountAll({
      offset: parseInt((params.page - 1) * params.limit),
      limit: parseInt(params.limit),
      where,
    });
  }
  async addCustomer(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.Customer.create({
        id: ulid.ulid(),
        tid: params.tid,
        name: params.name,
        address: params.address,
        telephone: params.telephone,
      });
      result.msg = 'create successful';
      return result;
    } catch (error) {
      result.msg = 'create fail,' + error;
      return result;
    }
  }
  async editCustomer(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.Customer.update({ name: params.name, address: params.address, telephone: params.telephone }, { where: { id: params.id } });
      result.msg = 'edit Customer successful';
      return result;
    } catch (error) {
      result.msg = 'edit Customer fail,' + error;
      return result;
    }
  }
  async deleteCustomer(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.Customer.destroy({
        where: { id: params.id },
      });
      result.msg = 'delete Customer successful';
      return result;
    } catch (error) {
      result.msg = 'delete Customer fail,' + error;
      return result;
    }
  }
  async bindCustomerList(params) {
    const Op = this.ctx.modelmysql.Sequelize.Op;
    const tid = params.tid;
    const where = {};
    where.tid = tid;
    where.onuId = null;
    if (params.name) {
      where.name = { [Op.like]: '%' + params.name + '%' };
    }
    return await this.ctx.modelmysql.Customer.findAndCountAll({
      offset: parseInt((params.page - 1) * params.limit),
      limit: parseInt(params.limit),
      where,
    });
  }
}

module.exports = CustomerService;
